import axios from 'axios';

document.addEventListener('DOMContentLoaded', async () => {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');

    const nameEl = document.getElementById('company-name');
    const loaderEl = document.getElementById('loader');
    const gridEl = document.getElementById('info-grid');
    const errorEl = document.getElementById('error-message');

    if (!code) {
        nameEl.textContent = '错误';
        loaderEl.style.display = 'none';
        errorEl.textContent = '错误：URL中未提供股票代码。请返回主页重试。';
        errorEl.style.display = 'block';
        return;
    }

    try {
        const response = await axios.get(`http://localhost:8000/api/stock/${code}/info`);
        const data = response.data;

        if (data.error) {
            throw new Error(data.error);
        }

        loaderEl.style.display = 'none';
        nameEl.textContent = `${data['股票简称'] || '未知公司'} (${data['股票代码'] || code})`;
        
        // 过滤掉不想显示或值为空的条目
        const filteredData = Object.entries(data).filter(([key, value]) => value && !key.includes('代码'));
        
        let content = '';
        for (const [key, value] of filteredData) {
            content += `
                <div class="info-item">
                    <span class="info-key">${key}</span>
                    <span class="info-value">${value}</span>
                </div>
            `;
        }
        gridEl.innerHTML = content;
        gridEl.style.display = 'grid';

    } catch (err) {
        nameEl.textContent = `加载失败 (${code})`;
        loaderEl.style.display = 'none';
        errorEl.textContent = `无法加载公司详情，请检查网络或后端服务。错误: ${err.message}`;
        errorEl.style.display = 'block';
    }
}); 